package bankapplication.com.acme.bankapp.domain.bank;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class BankReport {
  
  public static int getNbOfCustomers(Bank bank){
    return bank.getClients().size();
  }
  
  public static int getNbOfAccounts(Bank bank){
    int res = 0;
    Iterator<Client> clientiter = bank.getClients().iterator();
    while(clientiter.hasNext()){
      res +=clientiter.next().getAcconts().size();
    }
    return res;
  }
  
  public static List<Account> getAccountsSortedBySum(Bank bank){
      // XXX [MY] 'Collections.sort();' with Comparator is best way
    ArrayList<Account> reslist = new ArrayList<Account>(getNbOfAccounts(bank));
    Iterator<Client> clientiter = bank.getClients().iterator();
    while(clientiter.hasNext()){
      Iterator<Account> accountiter = clientiter.next().getAcconts().iterator();
      while(accountiter.hasNext()){
        reslist.add(accountiter.next());
      }
    }
    
    class SortByAccountBalance implements Comparator<Account> {
      @Override
      public int compare(Account a1, Account a2) {
        if(a1.getBalance() > a2.getBalance()){
          return 1;
        }
        else if(a1.getBalance() == a2.getBalance()){
          return 0;
        }
        return -1;
      }
    }
    Collections.sort(reslist, new SortByAccountBalance());
    return Collections.unmodifiableList(reslist);
  }
  
  public static double getBankCredit(Bank bank){
    double result = 0.0;
    Iterator<Client> clientiterator = bank.getClients().iterator();
    while(clientiterator.hasNext()){
      Iterator<Account> accountiterator = clientiterator.next().getAcconts().iterator();
      while(accountiterator.hasNext()){
        Account account = accountiterator.next();
        if(account instanceof CheckingAccount){
          result += ((CheckingAccount) account).getOverdraft();
        }
      }
    }
    return result;
  }

  public static Map<Client, Set<Account>> getCustomerAccount(Bank bank){
    HashMap<Client, Set<Account>> hashmap = new HashMap<Client, Set<Account>>(getNbOfCustomers(bank));
    Iterator<Client> clientiter = bank.getClients().iterator();
    while(clientiter.hasNext()){
      Client client = clientiter.next();
      hashmap.put(client, client.getAcconts());
    }
    return hashmap;
  }
  
}
